<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="账号" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入账号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="昵称" prop="nickName">
        <el-input v-model="queryParams.nickName" placeholder="请输入昵称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态 " prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态 " clearable>
          <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['ecs:agent:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-sort" size="mini" @click="toggleExpandAll">展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-if="refreshTable" v-loading="loading" :data="agentList" row-key="id" :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <el-table-column label="编号" width="100" align="center" prop="userId" />
      <el-table-column label="账号" align="center" prop="userName" />
      <el-table-column label="昵称" align="center" prop="nickName" />
      <el-table-column label="联系电话" align="center" prop="phoneNumber" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="状态 " align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="合作时间 " align="center" prop="cooperateDate" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-position" @click="handleProduct(scope.row)"
            v-hasPermi="['ecs:agent:edit']">费率配置</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['ecs:agent:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['ecs:agent:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>


    <!-- 添加或修改代理对话框 -->
    <el-drawer :wrapperClosable="false" :close-on-press-escape="false" :title="title" :visible.sync="open" size="35%"
      append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" class="form">
        <el-form-item label="上级代理" v-if="user.deptId === 100" :show-all-levels="false" prop="agentId">
          <el-select clearable @change="agentChange" v-model="computedValue" placeholder="请选择上级代理">
            <el-option v-for="item in agentOptions" :key="item.id" :value="item.id" :label="item.nickName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="代理昵称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入代理昵称" maxlength="30" />
        </el-form-item>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="代理账号" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入代理账号" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="代理密码" prop="password" v-if="!form.id" :rules='[
              { required: true, message: "密码不能为空", trigger: "blur" },
              { min: 5, max: 20, message: "密码长度必须介于 5 和 20 之间", trigger: "blur" },
            ]'>
              <el-input v-model="form.password" placeholder="请输入代理密码" type="password" maxlength="20" show-password />
            </el-form-item>
            <el-form-item label="代理密码" prop="password" v-else :rules='[
              { min: 5, max: 20, message: "密码长度必须介于 5 和 20 之间", trigger: "blur" },
            ]'>
              <el-input v-model="form.password" placeholder="请输入代理密码" type="password" maxlength="20" show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="联系电话" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入联系电话" maxlength="11" />
        </el-form-item>
        <!--        <el-form-item label="代理费率" prop="feeRate">-->
        <!--          <el-input-number :step="0.1" :min="0" :max="15" :precision="2" v-model.number="form.feeRate" placeholder="请输入代理费率" />-->
        <!--        </el-form-item>-->
        <el-form-item label="合作时间">
          <el-date-picker v-model="form.cooperateDate" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" type="date"
            placeholder="请选择合作时间"> </el-date-picker>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label
              }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="user.deptId === 100" label="发展下级" prop="isOperate">
          <el-radio-group :disabled="form.agentId > 0" v-model="form.isOperate">
            <el-radio v-for="dict in dict.type.yes_no" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-table :data="productList" v-if="!form.id">
          <el-table-column label="编码" align="center" prop="id" />
          <el-table-column label="名称" align="center" prop="name" />
          <el-table-column label="代理费率/%" width="210" align="center" prop="feeRate">
            <template slot-scope="{ row }">
              <el-form :model="row" ref="tableForm">
                <el-form-item prop="splitFeeRate" :rules='[
                  { required: true, message: "代理费率不能为空", trigger: "blur" },
                  { type: "number", message: "代理费率为数字", trigger: "blur" },
                ]'>
                  <el-input-number :step="0.1" :min="0" :max="15" size="mini" :precision="2" v-model="row.splitFeeRate"
                    placeholder="请输入代理费率" />
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div class="footer-operation">
        <el-button type="primary" @click="submitForm" v-clickOnce>确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-drawer>

    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" title="代理费率配置" :visible.sync="openProduct"
      width="45%" append-to-body>
      <el-table v-loading="loading" :data="productList">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="编码" align="center" prop="id" />
        <el-table-column label="名称" align="center" prop="name" />
        <el-table-column label="代理费率/%" width="210" align="center" prop="feeRate">
          <template slot-scope="{ row }">
            <el-form v-if="row.id === editProductId" :model="row" ref="tableForm">
              <el-form-item prop="splitFeeRate" :rules='[
                { required: true, message: "代理费率不能为空", trigger: "blur" },
                { type: "number", message: "代理费率为数字", trigger: "blur" },
              ]'>
                <el-input-number :step="0.1" :min="0" :max="15" size="mini" :precision="2" v-model="row.splitFeeRate"
                  placeholder="请输入代理费率" />
              </el-form-item>
            </el-form>
            <template v-else>{{ row.splitFeeRate ? row.splitFeeRate : 0 }}%</template>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="{ row }">
            <div v-if="row.id !== editProductId">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleProductUpdate(row)"
                v-hasPermi="['ecs:userProduct:edit']">修改</el-button>
            </div>
            <div v-else>
              <el-button size="mini" type="text" @click="handProductSave(row)" v-clickOnce>保存</el-button>
              <el-button size="mini" type="text" @click="handProductCancel(row)">取消</el-button>
            </div>

          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

  </div>
</template>

<script>
import { listAgent, getAgent, delAgent, addAgent, updateAgent, getAgentUserId } from '@/api/ecs/agent'
import { getUserProfile } from '@/api/system/user'
import { listProduct } from '@/api/ecs/product'
import { updateUserProduct } from '@/api/ecs/userProduct'

export default {
  name: "Agent",
  dicts: ['sys_normal_disable', 'yes_no'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 代理表格数据
      agentList: [],
      editProductId: 0,
      productList: [],
      openProduct: false,
      // 是否展开，默认全部折叠
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      agentOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: '',
        nickName: '',
        status: null
      },
      user: {},
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "代理账号不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '代理账号长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: "代理昵称不能为空", trigger: "blur" }
        ],
        phoneNumber: [
          { required: true, message: "代理联系电话不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的联系电话",
            trigger: "blur"
          }
        ],
        password: [
          // { required: true, message: "密码不能为空", trigger: "blur" },
          // { min: 5, max: 20, message: '密码长度必须介于 5 和 20 之间', trigger: 'blur' },
          { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur" }
        ],
      }
    };
  },
  computed: {
    // 计算属性：将 0 映射为 null 显示为空
    computedValue: {
      get() {
        return this.form.agentId === 0 ? null : this.form.agentId;
      },
      set(val) {
        this.form.agentId = val || 0;
      },
    },
  },
  created() {
    this.getUser();
    this.getList();
  },
  methods: {
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
        if (this.user.deptId === 100) {
          this.form.isOperate = "1"
        } else {
          this.form.isOperate = "2"
        }
      });
    },
    agentChange(e) {
      if (e) {
        this.form.isOperate = "2"
      }
    },
    /** 查询代理列表 */
    getList() {
      this.loading = true;
      listAgent(this.queryParams).then(response => {
        if (response.data) {
          this.agentList = this.handleTree(response.data, "id", "agentId");
        }
        this.loading = false;
      });
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.nickName,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        agentId: null,
        platformId: null,
        userId: null,
        feeRate: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        delFlag: null,
        status: "0",
        password: null,
        remark: null,
        isOperate: "1",
        phoneNumber: null,
        cooperateDate: null
      };
      if (this.user.deptId === 100) {
        this.form.isOperate = "1"
      } else {
        this.form.isOperate = "2"
      }
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    getTreeselect() {
      listAgent({ agentId: 0 }).then(response => {
        this.agentOptions = response.data
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();

      this.getTreeselect()
      this.open = true;
      this.title = "添加代理";
      listProduct().then(response => {
        this.productList = response.rows;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect()
      const id = row.id || this.ids

      getAgent(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改代理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAgent(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.productList = this.productList
            addAgent(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除编号为"' + row.id + '"，昵称为"' + row.nickName + '"的代理？').then(function () {
        return delAgent(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    handleProduct(row) {
      this.openProduct = true;
      this.form.id = row.id
      this.editProductId = 0
      listProduct({ splitId: row.id, type: 2 }).then(response => {
        this.productList = response.rows;
      });
    },
    handleProductUpdate(row) {
      this.productData = { ...row }
      if (!row.splitFeeRate) {
        row.splitFeeRate = 0
      }
      this.editProductId = row.id
    },
    handProductSave(row) {
      this.$refs["tableForm"].validate(valid => {
        if (valid) {
          updateUserProduct({ productId: row.id, splitId: this.form.id, splitFeeRate: row.splitFeeRate, type: 2 }).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.editProductId = 0
            this.handleProduct();
          });
        }
      })
    },
    handProductCancel(row) {
      Object.assign(row, this.productData)
      this.editProductId = 0
    },
  }
};
</script>
<style scoped lang="scss">
.form {
  padding-left: 10px;
  padding-right: 10px;
  padding-bottom: 80px;
}

.footer-operation {
  bottom: 0;
  width: 100%;
  height: 80px;
  display: flex;
  z-index: 10000;
  padding: 0 20px;
  text-align: center;
  position: absolute;
  align-items: center;
  background-color: #ffffff;
  border-top: 1px solid #EBEEF5;

  .el-button {
    width: 100%;
  }
}
</style>
